const vscode = require('vscode');
const path = require('path');
const fs = require('fs');
const { exec } = require('child_process');

/**
 * 插件激活函数
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {
    console.log('JSZ Language Support 插件已激活');

    // 注册翻译命令
    const translateCommand = vscode.commands.registerCommand('jsz.translate', async () => {
        const activeEditor = vscode.window.activeTextEditor;
        if (!activeEditor) {
            vscode.window.showErrorMessage('请先打开一个 JSZ 文件');
            return;
        }

        const document = activeEditor.document;
        if (document.languageId !== 'jsz') {
            vscode.window.showErrorMessage('当前文件不是 JSZ 格式');
            return;
        }

        await translateJSZFile(document);
    });

    // 注册格式化命令
    const formatCommand = vscode.commands.registerCommand('jsz.format', async () => {
        const activeEditor = vscode.window.activeTextEditor;
        if (!activeEditor) {
            vscode.window.showErrorMessage('请先打开一个 JSZ 文件');
            return;
        }

        const document = activeEditor.document;
        if (document.languageId !== 'jsz') {
            vscode.window.showErrorMessage('当前文件不是 JSZ 格式');
            return;
        }

        await formatJSZFile(activeEditor);
    });

    // 注册自动补全提供器
    const completionProvider = vscode.languages.registerCompletionItemProvider(
        'jsz',
        new JSZCompletionItemProvider(),
        '.'
    );

    // 注册悬停提供器
    const hoverProvider = vscode.languages.registerHoverProvider(
        'jsz',
        new JSZHoverProvider()
    );

    // 注册文档符号提供器
    const documentSymbolProvider = vscode.languages.registerDocumentSymbolProvider(
        'jsz',
        new JSZDocumentSymbolProvider()
    );

    // 监听文件保存事件，自动翻译
    const onSaveListener = vscode.workspace.onDidSaveTextDocument(async (document) => {
        if (document.languageId === 'jsz') {
            const config = vscode.workspace.getConfiguration('jsz');
            const autoTranslate = config.get('autoTranslateOnSave', false);
            
            if (autoTranslate) {
                await translateJSZFile(document);
            }
        }
    });

    context.subscriptions.push(
        translateCommand,
        formatCommand,
        completionProvider,
        hoverProvider,
        documentSymbolProvider,
        onSaveListener
    );
}

/**
 * 翻译 JSZ 文件
 * @param {vscode.TextDocument} document
 */
async function translateJSZFile(document) {
    const config = vscode.workspace.getConfiguration('jsz');
    const translatorPath = config.get('translatorPath', '');
    const outputDir = config.get('outputDirectory', 'output');

    if (!translatorPath) {
        vscode.window.showErrorMessage('请先在设置中配置 JSZ 翻译器路径');
        return;
    }

    const filePath = document.fileName;
    const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri);
    const outputPath = workspaceFolder 
        ? path.join(workspaceFolder.uri.fsPath, outputDir)
        : path.join(path.dirname(filePath), outputDir);

    // 确保输出目录存在
    if (!fs.existsSync(outputPath)) {
        fs.mkdirSync(outputPath, { recursive: true });
    }

    const command = `"${translatorPath}" "${filePath}"`;
    
    vscode.window.withProgress({
        location: vscode.ProgressLocation.Notification,
        title: "正在翻译 JSZ 文件...",
        cancellable: false
    }, async (progress) => {
        return new Promise((resolve, reject) => {
            exec(command, { cwd: path.dirname(filePath) }, (error, stdout, stderr) => {
                if (error) {
                    vscode.window.showErrorMessage(`翻译失败: ${error.message}`);
                    reject(error);
                    return;
                }

                if (stderr) {
                    console.warn('翻译警告:', stderr);
                }

                vscode.window.showInformationMessage('JSZ 文件翻译完成');
                resolve();
            });
        });
    });
}

/**
 * 格式化 JSZ 文件
 * @param {vscode.TextEditor} editor
 */
async function formatJSZFile(editor) {
    const document = editor.document;
    const text = document.getText();
    
    // 简单的格式化逻辑
    const formattedText = formatJSZCode(text);
    
    const edit = new vscode.WorkspaceEdit();
    const fullRange = new vscode.Range(
        document.positionAt(0),
        document.positionAt(text.length)
    );
    
    edit.replace(document.uri, fullRange, formattedText);
    await vscode.workspace.applyEdit(edit);
    
    vscode.window.showInformationMessage('JSZ 文件格式化完成');
}

/**
 * 格式化 JSZ 代码
 * @param {string} code
 * @returns {string}
 */
function formatJSZCode(code) {
    let formatted = code;
    let indentLevel = 0;
    const lines = formatted.split('\n');
    const formattedLines = [];

    for (let line of lines) {
        const trimmedLine = line.trim();
        
        if (trimmedLine === '') {
            formattedLines.push('');
            continue;
        }

        // 减少缩进
        if (trimmedLine.includes('}') || trimmedLine.includes('否则')) {
            indentLevel = Math.max(0, indentLevel - 1);
        }

        // 添加缩进
        const indent = '    '.repeat(indentLevel);
        formattedLines.push(indent + trimmedLine);

        // 增加缩进
        if (trimmedLine.includes('{') || 
            trimmedLine.includes('如果') || 
            trimmedLine.includes('当') || 
            trimmedLine.includes('为') ||
            trimmedLine.includes('函数')) {
            indentLevel++;
        }
    }

    return formattedLines.join('\n');
}

/**
 * JSZ 自动补全提供器
 */
class JSZCompletionItemProvider {
    provideCompletionItems(document, position, token, context) {
        const completionItems = [];

        // 中文关键字补全
        const chineseKeywords = [
            { label: '如果', insertText: '如果 (${1:条件}) {\n\t${2}\n}', kind: vscode.CompletionItemKind.Keyword },
            { label: '否则', insertText: '否则', kind: vscode.CompletionItemKind.Keyword },
            { label: '当', insertText: '当 (${1:条件}) {\n\t${2}\n}', kind: vscode.CompletionItemKind.Keyword },
            { label: '为', insertText: '为 (${1:初始化}; ${2:条件}; ${3:更新}) {\n\t${4}\n}', kind: vscode.CompletionItemKind.Keyword },
            { label: '函数', insertText: '函数 ${1:名称}(${2:参数}) {\n\t${3}\n}', kind: vscode.CompletionItemKind.Keyword },
            { label: '变量', insertText: '变量 ${1:名称} = ${2:值};', kind: vscode.CompletionItemKind.Keyword },
            { label: '常量', insertText: '常量 ${1:名称} = ${2:值};', kind: vscode.CompletionItemKind.Keyword },
            { label: '类', insertText: '类 ${1:名称} {\n\t${2}\n}', kind: vscode.CompletionItemKind.Keyword },
            { label: '返回', insertText: '返回 ${1:值};', kind: vscode.CompletionItemKind.Keyword },
            { label: '中断', insertText: '中断;', kind: vscode.CompletionItemKind.Keyword },
            { label: '继续', insertText: '继续;', kind: vscode.CompletionItemKind.Keyword },
            { label: '尝试', insertText: '尝试 {\n\t${1}\n} 捕获 (${2:错误}) {\n\t${3}\n}', kind: vscode.CompletionItemKind.Keyword },
            { label: '捕获', insertText: '捕获 (${1:错误}) {\n\t${2}\n}', kind: vscode.CompletionItemKind.Keyword },
            { label: '抛出', insertText: '抛出 ${1:错误};', kind: vscode.CompletionItemKind.Keyword },
            { label: '新建', insertText: '新建 ${1:类型}(${2:参数})', kind: vscode.CompletionItemKind.Keyword },
            { label: '导入', insertText: '导入 { ${1:模块} } 从 \'${2:路径}\';', kind: vscode.CompletionItemKind.Keyword },
            { label: '导出', insertText: '导出 ${1:内容};', kind: vscode.CompletionItemKind.Keyword },
            { label: '异步', insertText: '异步 ', kind: vscode.CompletionItemKind.Keyword },
            { label: '等待', insertText: '等待 ${1:异步操作}', kind: vscode.CompletionItemKind.Keyword }
        ];

        chineseKeywords.forEach(keyword => {
            const item = new vscode.CompletionItem(keyword.label, keyword.kind);
            item.insertText = new vscode.SnippetString(keyword.insertText);
            item.documentation = `JSZ 中文关键字: ${keyword.label}`;
            completionItems.push(item);
        });

        return completionItems;
    }
}

/**
 * JSZ 悬停提供器
 */
class JSZHoverProvider {
    provideHover(document, position, token) {
        const range = document.getWordRangeAtPosition(position);
        if (!range) return;

        const word = document.getText(range);
        const keywordMap = {
            '如果': 'if - 条件语句',
            '否则': 'else - 否则语句',
            '当': 'while - 循环语句',
            '为': 'for - 循环语句',
            '函数': 'function - 函数定义',
            '变量': 'var/let - 变量声明',
            '常量': 'const - 常量声明',
            '类': 'class - 类定义',
            '返回': 'return - 返回语句',
            '中断': 'break - 中断语句',
            '继续': 'continue - 继续语句',
            '尝试': 'try - 异常处理',
            '捕获': 'catch - 异常捕获',
            '抛出': 'throw - 抛出异常',
            '新建': 'new - 创建实例',
            '导入': 'import - 导入模块',
            '导出': 'export - 导出模块',
            '异步': 'async - 异步函数',
            '等待': 'await - 等待异步操作'
        };

        if (keywordMap[word]) {
            return new vscode.Hover(
                new vscode.MarkdownString(`**${word}**\n\n${keywordMap[word]}`)
            );
        }
    }
}

/**
 * JSZ 文档符号提供器
 */
class JSZDocumentSymbolProvider {
    provideDocumentSymbols(document, token) {
        const symbols = [];
        const text = document.getText();
        const lines = text.split('\n');

        for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            const trimmedLine = line.trim();

            // 函数定义
            const functionMatch = trimmedLine.match(/函数\s+(\w+)\s*\(/);
            if (functionMatch) {
                const symbol = new vscode.DocumentSymbol(
                    functionMatch[1],
                    '函数',
                    vscode.SymbolKind.Function,
                    new vscode.Range(i, 0, i, line.length),
                    new vscode.Range(i, 0, i, line.length)
                );
                symbols.push(symbol);
            }

            // 类定义
            const classMatch = trimmedLine.match(/类\s+(\w+)/);
            if (classMatch) {
                const symbol = new vscode.DocumentSymbol(
                    classMatch[1],
                    '类',
                    vscode.SymbolKind.Class,
                    new vscode.Range(i, 0, i, line.length),
                    new vscode.Range(i, 0, i, line.length)
                );
                symbols.push(symbol);
            }

            // 变量定义
            const variableMatch = trimmedLine.match(/(变量|常量)\s+(\w+)/);
            if (variableMatch) {
                const symbol = new vscode.DocumentSymbol(
                    variableMatch[2],
                    variableMatch[1],
                    vscode.SymbolKind.Variable,
                    new vscode.Range(i, 0, i, line.length),
                    new vscode.Range(i, 0, i, line.length)
                );
                symbols.push(symbol);
            }
        }

        return symbols;
    }
}

/**
 * 插件停用函数
 */
function deactivate() {
    console.log('JSZ Language Support 插件已停用');
}

module.exports = {
    activate,
    deactivate
};